# API 调用实例

import os
from openai import OpenAI
import requests
import base64
import logging


class apiOpenAi():
    def __init__(self, api_key, base_url, model_id):
        self.apiKey = api_key
        self.baseUrl = base_url
        self.modelId = model_id
        self.err = ''

    def clientChatText(self, reqText):
        # 文本聊天
        try:
            client = OpenAI(
                api_key=self.apiKey,
                base_url=self.baseUrl,
            )
            completion = client.chat.completions.create(
                model=self.modelId,
                messages=[
                    {
                        'role': 'system',
                        'content': 'You are a helpful assistant.'
                    },
                    {
                        'role': 'user',
                        'content': reqText
                    }
                ],
                stream=True
            )
            for chunk in completion:
                print(chunk.choices[0].delta.content, end='', flush=True)

        except Exception as e:
            self.err = f"错误信息：{e}"
            print(self.err)

    def clientChatImage(self, reqText, reqImage):
        # 图片聊天
        print('%s->%s' % (reqText, reqImage))
        if os.path.isfile(reqImage):
            # 本地图片文件
            url = '%smodels/%s/invoke' % (self.baseUrl, self.modelId)
            print(url)
            try:
                # logging.basicConfig(level=logging.INFO)
                # Open the image file in binary mode and encode it to Base64
                with open(reqImage, "rb") as img_file:
                    encoded_image = base64.b64encode(img_file.read()).decode('utf-8')
                # 构造消息内容
                messages = [{
                    'role': 'user',
                    'content': [
                        {
                            'type': 'text',
                            'text': reqText,
                        },
                        {
                            'type': 'image',
                            'image': {
                                'base64': encoded_image,
                            },
                        }
                    ],
                }]

                # Prepare payload
                payload = {
                    "messages": messages
                }

                # Prepare headers
                headers = {
                    "Authorization": f"Bearer {self.apiKey}",
                    "Content-Type": "application/json"
                }

                # Send POST request to the API
                response = requests.post(url, json=payload, headers=headers)

                # Check response status and print result
                if response.status_code == 200:
                    print("Success: %s" % (response.json()))
                    # logging.info("Success: %s", response.json())
                else:
                    print("Error: %s %s" % (response.status_code, response.text))
                    # logging.error("Error: %s %s", response.status_code, response.text)
            except FileNotFoundError:
                print("The specified image file was not found.")
                # logging.error("The specified image file was not found.")
            except Exception as e:
                print("An error occurred: %s" % (str(e)))
                # logging.error("An error occurred: %s", str(e))


        else:
            # 远程图片url
            try:
                client = OpenAI(
                    api_key=self.apiKey,
                    base_url=self.baseUrl,
                )
                completion = client.chat.completions.create(
                    model=self.modelId,
                    messages=[{
                        'role':
                            'user',
                        'content': [{
                            'type': 'text',
                            'text': reqText,
                        }, {
                            'type': 'image_url',
                            'image_url': {
                                'url':
                                    reqImage,
                            },
                        }],
                    }],
                    stream=True
                )
                for chunk in completion:
                    print(chunk.choices[0].delta.content, end='', flush=True)
            except Exception as e:
                self.err = f"错误信息：{e}"
                print(self.err)


if __name__ == '__main__':
    print('modelscope api test')
    api = apiOpenAi('d3f6c5cd-7c56-4c6b-809e-36ed52d58f8b',
                    'https://api-inference.modelscope.cn/v1/',
                    'Qwen/Qwen2.5-VL-72B-Instruct')
    # 'Qwen/Qwen2.5-72B-Instruct')
    # api.clientChatText('你好')
    image_text = '描述这幅图'
    image_url = 'https://modelscope.oss-cn-beijing.aliyuncs.com/demo/images/audrey_hepburn.jpg'
    # image_url = 'http://192.168.1.1/haidian_data/xishan/PH1.7-1-005/005-0000001A.jpg'
    api.clientChatImage(image_text, image_url)
    # api.clientChatImage('获取图片文本信息',
    #                     'f:/Image/ocrTest/id0.jpg')

# models = ['qwen-max',  # 适合复杂任务，推理能力最强
#           'qwen-plus',  # 效果,速度,成本均衡
#           'qwen-turbo',  # 适合简单任务，速度快、成本极低
#           'qwen-long'  # 适合大规模文本分析，效果与速度均衡、成本较低
#           ]
